<template>
  <div style="width: 650px; height: 300px" ref="charts"></div>
</template>

<script>
// 引入图形可视化库
import echarts from "echarts";
import { mapGetters } from "vuex";
export default {
  name: "SaleBarCharts",
  props: ["activeName"],
  computed: {
    title() {
      return this.activeName === "sell" ? "销售额" : "访问量";
    },
    ...mapGetters("home", [
      "orderFullYearAxis",
      "orderFullYear",
      "userFullYearAxis",
      "userFullYear",
    ]),
  },
  methods: {
    initMyCharts() {
      // 初始化
      this.myCharts = echarts.init(this.$refs.charts);
      // 每次重新绘制时，清空上一个柱状图，使其保证每次数据加载时都有动画
      this.myCharts.clear();
      // 配置
      this.myCharts.setOption({
        title: {
          text: this.title + "趋势",
        },
        xAxis: {
          type: "category",
          data: [],
          // 调整x轴刻度位置
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
        },
        // 动画效果
        animation: 500,
        series: [
          {
            data: [],
            type: "bar",
            // 柱条的宽度，不设就自适应
            barWidth: 40,
            itemStyle: {
              color: "#99ce31",
            },
          },
        ],
        // 图形距离容器的距离配置
        grid: {
          left: 40,
          top: 60,
          right: 0,
          bottom: 25,
        },
      });
    },
  },
  watch: {
    // 监听mock数据的变化（从无到有）
    orderFullYear() {
      this.myCharts.setOption({
        xAxis: {
          type: "category",
          data: this.orderFullYearAxis,
          // 调整x轴刻度位置
          axisTick: {
            alignWithLabel: true,
          },
        },
        series: [
          {
            data: this.orderFullYear,
            type: "bar",
            // 柱条的宽度，不设就自适应
            barWidth: 40,
            itemStyle: {
              color: "#99ce31",
            },
          },
        ],
      });
    },
    // 监听标题的变化
    title() {
      const dataList =
        this.title === "销售额" ? this.orderFullYear : this.userFullYear;
      const xAxisData =
        this.title === "销售额"
          ? this.orderFullYearAxis
          : this.userFullYearAxis;
      this.myCharts.setOption({
        title: {
          text: this.title + "趋势",
        },
        xAxis: {
          type: "category",
          data: xAxisData,
        },
        series: [
          {
            data: dataList,
            type: "bar",
            // 柱条的宽度，不设就自适应
            barWidth: 40,
            itemStyle: {
              color: "#99ce31",
            },
          },
        ],
      });
    },
  },
  mounted() {
    // 挂载完毕，绘制出柱状图
    this.initMyCharts();
  },
};
</script>

<style>
</style>